package com.twu.biblioteca.behavior;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.twu.biblioteca.Book;
import com.twu.biblioteca.Library;

import java.util.List;
import java.util.NoSuchElementException;

public class ReserveBehavior implements Behavior {
    private static final String SUCCESS_MESSAGE = "Thank You! Enjoy the book.";
    private static final String FAIL_MESSAGE = "Sorry we don't have that book yet.";

    private final int bookIndex;

    public ReserveBehavior(int bookIndex) {
        this.bookIndex = bookIndex;
    }

    @Override
    public void execute() {
        Book book = findBook();
        if (null != book) {
            book.reserve();
            System.out.println(SUCCESS_MESSAGE);
        } else {
            System.out.println(FAIL_MESSAGE);
        }
    }

    @Override
    public Behavior nextBehavior() {
        return new ListMenuOptionBehavior();
    }

    @Override
    public String getMessage() {
        return findBook() == null ? FAIL_MESSAGE : SUCCESS_MESSAGE;
    }

    Book findBook() {
        List<Book> books = Library.getInstance().getBooks();
        Book book = null;
        if (bookIndex <= books.size() && bookIndex > 0) {
            book = books.get(bookIndex - 1);
            book = book.isReserved() ? null : book;
        }
        return book;
    }
}
